package leetcode.q21;

import leetcode.ListNode;

/**
 * <a href="https://leetcode.cn/problems/merge-two-sorted-lists/description/">...</a>
 * 21. 合并两个有序链表
 *  将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return list1;

        ListNode dummyHead = new ListNode(-1);
        ListNode cur = dummyHead;

        ListNode cur1 = list1;
        ListNode cur2 = list2;
        while (true) {
            if (cur1 == null && cur2 == null) break;
            if (cur2 == null) {
                cur.next = new ListNode(cur1.val);
                cur = cur.next;
                cur1 = cur1.next;
                continue;
            }
            if (cur1 == null) {
                cur.next = new ListNode(cur2.val);
                cur = cur.next;
                cur2 = cur2.next;
                continue;
            }
            if (cur1.val <= cur2.val) {
                cur.next = new ListNode(cur1.val);
                cur1=cur1.next;
            }else {
                cur.next = new ListNode(cur2.val);
                cur2=cur2.next;
            }
            cur = cur.next;
        }
        return dummyHead.next;
    }

    public static void main(String[] args) {
        ListNode head = new Solution().mergeTwoLists(
                new ListNode(1,2,3,4),
                new ListNode(2,4,5));

        System.out.println(head);

    }
}